<template>
  <div class="container" :style="containerStyle">
    <navbar ref="navbar" title="我的选品库" theme="light" :rightItemText="!editMode ? '编辑' : '取消'" @rightItemClick="navbarRightItemClick"></navbar>
    <list class="item-list-container"
          @scroll="onPageScroll">
      <page-refresh v-on:refresh="onXRefresh" v-on:pullingDown="onPullingDown" :refreshing="refreshing"
                    :indicatorScale="indicatorScale"></page-refresh>
      <cell>
        <div style="margin-top: 12" ref="top"></div>
      </cell>
      <template v-if="userItemSelectionList.length" v-for="(userItemSelection, rowIdx) in userItemSelectionList">
        <header v-bind:key="rowIdx">
          <div class="user-info">
            <div class="user-info-left">
              <image :src="userItemSelection.userAvatarUrl" class="user-info-avatar"></image>
              <div class="user-info-detail">
                <text class="user-info-nickname">{{userItemSelection.userNickname}}</text>
                <text class="user-info-time-info">{{userItemSelection.timeInfo.value + userItemSelection.timeInfo.typeTitle}}前</text>
              </div>
            </div>
            <text class="item-selection-share-btn icon" v-if="!editMode" @click="share(userItemSelection)">&#xe608;{{userItemSelection.shareTimes}}</text>
            <text class="item-selection-share-btn icon" v-if="editMode" @click="del(userItemSelection)">删除</text>
          </div>
        </header>
        <cell v-bind:key="rowIdx">
          <div class="item-selection-panel">
            <text class="item-selection-content" v-if="userItemSelection.content">{{userItemSelection.content}}</text>
            <div class="item-selection-row" v-bind:key="itemListIdx" v-for="(itemList, itemListIdx) in grouping(userItemSelection.itemList, 3, {})">
              <div class="item-selection"  v-for="(item) in itemList" :style="{width: itemWidth + 'px', visibility: item.id ? 'visible': 'hidden'}"
                   @click="commissionItemClick(item)"
                   v-bind:key="item.id">
                <image :src="item.picUrl" :style="{width: itemWidth + 'px', height: itemWidth + 'px'}" class="item-pic"></image>
                <div class="detail-row">
                  <div class="price">
                    <text class="price-y">¥</text>
                    <text class="price-val">{{item.price}}</text>
                  </div>
                  <text class="origin-price">¥{{item.originPrice}}</text>
                </div>
              </div>
            </div>
          </div>
        </cell>
      </template>
      <cell>
        <page-notice msg="抱歉，什么都木有找到～" :icon="sorryIcon" v-if="!userItemSelectionList.length  && !hasNext"></page-notice>
      </cell>
      <page-loading-more v-on:loadingMore="onLoadingMore" :loadingMore="loadingMore"
                         :shown="hasNext"></page-loading-more>
    </list>
    <page-scrolltop :shown="pageScrollTopShown" @click="gotoTop"></page-scrolltop>
    <wxc-loading :show="loadingShow"></wxc-loading>
    <wxc-dialog title="温馨提示"
                content="确认删除吗？"
                :show="dialogShow"
                :single="false"
                @wxcDialogCancelBtnClicked="wxcDialogCancelBtnClicked"
                @wxcDialogConfirmBtnClicked="wxcDialogConfirmBtnClicked">
    </wxc-dialog>
  </div>
</template>
<style lang="scss">
  @import "./sass/var";
  @import "./sass/mixin";
  @import "./sass/buttons";
  @import "./sass/icon";

  .container {
    background-color: $body-bg;
    transition: transform .3s linear;
  }
  .item-list-container {
    /*background-color: #FFFFFF;*/
  }

  .user-info {
    padding: 10px;
    background-color: #FFFFFF;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    &-left {
      flex-direction: row;
      align-items: center;
    }
    &-avatar {
      width: 80px;
      height: 80px;
      border-radius: 80px;
    }
    &-detail {
      justify-content: space-around;
      padding-left: 20px;
    }
    &-nickname {
      font-size: 28px;
      color: $color-warning;
    }
    &-time-info {
      font-size: 20px;
      color: $color-muted;
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    right: 0;
    left: 0;
    padding: 20px;
    flex-direction: row;
  }

  .item-selection {
    position: relative;
    &-panel {
      background-color: #FFFFFF;
      margin-bottom: 12px;
    }
    &-row {
      flex-direction: row;
      justify-content: space-between;
      padding: 0 10px 10px 10px;
      background-color: #FFFFFF;
    }
    &-content {
      padding:  10px 10px 20px 10px;
      font-weight: 300;
      font-size: 28px;
      color: $color;
      line-height: 32px;
    }
    &-share-btn {
      @include border(1, solid, $brand-primary);
      color: $color-primary;
      height: 40px;
      padding: 0 15px;
      border-radius: 40px;
      line-height: 40px;
      font-weight: 300;
      text-align: center;
      font-size: 24px;
      background-color: transparent;
      &:active {
        background-color: $color-primary;
        color: #FFFFFF;
      }
    }
  }

  .topbar {
    position: absolute;
    top: 0;
    right: 0;
    padding: 10px;
    left: 0;
    align-items: center;
    justify-content: flex-end;
    justify-items: flex-end;
    flex-direction: row;
    &-btn {
      margin-left: 10px
    }
  }

  .detail-row {
    flex-direction: row;
    justify-content: space-between;
    padding: 5px 10px;
    align-items: center;
    position: absolute;
    bottom: 5px;
    right: 5px;
    background-color: $brand-primary;
    border-bottom-left-radius: 20px;
    border-top-right-radius: 20px;
  }
  .origin-price {
    color: #f1f1f1;
    padding-left: 5px;
    font-size: 20px;
    text-decoration: line-through;
    font-weight: 100;
  }
  .price {
    flex-direction: row;
    align-items: flex-end;
    &-y {
      font-size: 24px;
      color: #fff;
      font-weight: 100;
    }
    &-val {
      color: #fff;
      font-size: 32px;
    }
  }

  .btn-del{
    font-size: 28px;
    color: #FFFFFF;
  }

  .textarea {
    font-size: 28px;
    line-height: 32px;
    color: $color;
    background-color: #f5f5f5;
    padding: 20px;
  }
</style>
<script>

import {WxcLoading, WxcDialog} from 'weex-ui'
let api = require('./include/api')
let Deferred = require('Deferred')
let dom = weex.requireModule('dom')
let urlPath = require('./include/url-path')
let navigator = require('./include/xnavigator')
let grouping = require('./include/grouping')
let modal = weex.requireModule('modal')
let paddingValue = [0, 12, 40]
let DEFAULT_ITEM_SEARCH_PARAM = {
  page: 1,
  pageSize: 10
}
module.exports = {
  mixins: [
    require('./mixin/page-refresh'),
    require('./mixin/page-scrolltop'),
    require('./mixin/page-loading-more')
  ],
  components: {
    'page-notice': require('./components/page-notice.vue'),
    'navbar': require('./components/navbar.vue'),
    WxcLoading,
    WxcDialog
  },
  props: {
    height: {default: 0},
    back: {default: true},
    recommend: {default: ''},
    title: {default: null}
  },
  data () {
    return {
      userItemSelectionList: [],
      refreshing: false,
      refreshIndicatorScale: 0.2,
      sorryIcon: 'images/aiya.png',
      loadingShow: false,
      itemWidth: 750,
      column: 3,
      content: '',
      dialogContent: '',
      saveDoing: false,
      createResultDialogShow: false,
      hasNext: true,
      searchParam: {},
      lxkAvatar: urlPath.assets('images/logo_la_t_200.png?v=2'),
      editMode: false,
      dialogShow: false,
      currentUserItemSelection: null
    }
  },
  created () {
    this.itemWidth = (750 - paddingValue[this.column - 1]) / this.column
    this.sorryIcon = urlPath.assets(this.sorryIcon)
    Object.assign(this.searchParam, DEFAULT_ITEM_SEARCH_PARAM)
    Deferred.when(this.loadData(), this.search()).always(() => {
    })
  },
  methods: {
    loadData () {

    },
    grouping: grouping,
    resetSearchParam () {
      Object.assign(this.searchParam, DEFAULT_ITEM_SEARCH_PARAM)
      this.hasNext = true
    },
    search (append) {
      return api.userItemSelection.search(this.searchParam).done(rs => {
        setTimeout(() => {
          let data = rs.data
          if (append) {
            this.userItemSelectionList = this.userItemSelectionList.concat(data.results)
          } else {
            this.userItemSelectionList = data.results
          }

          this.hasNext = data.hasNext
        }, 200)
      })
    },
    getShareContent (content) {
      if (content) {
        content += '\n----------------\n'
      }
      content += '长按图片识别二维码，复制淘口令打开手机淘宝，领券购买！'
      return content
    },
    onXRefresh (event) {
      this.resetSearchParam()
      this.onRefresh(event, Deferred.when(this.loadData(), this.search()))
    },
    onLoadingMore (event) {
      this.loadingMore = true
      this.searchParam.page = this.searchParam.page + 1
      this.search(true).done(() => {
        this.loadingMore = false
      })
    },
    gotoTop () {
      dom.scrollToElement(this.$refs.top)
    },
    onPageScroll (event) {
      this.onPageScrollForScrollTop(event)
    },
    commissionItemClick (item) {
      navigator.push('commission-item.js?id=' + item.id)
    },
    navbarRightItemClick () {
      this.editMode = !this.editMode
    },
    del (selection) {
      this.dialogShow = true
      this.currentUserItemSelection = selection
    },
    wxcDialogCancelBtnClicked () {
      this.dialogShow = false
    },
    wxcDialogConfirmBtnClicked () {
      this.loadingShow = true
      this.dialogShow = false
      api.userItemSelection.del({id: this.currentUserItemSelection.id}).done(rs => {
        for (var i = 0; i < this.userItemSelectionList.length; i++) {
          if (this.userItemSelectionList[i].id === this.currentUserItemSelection.id) {
            this.userItemSelectionList.splice(i, 1)
            break
          }
        }
        if (this.userItemSelectionList.length === 0) {
          this.search()
          this.editMode = false
        }
      }).always(rs => {
        this.loadingShow = false
      })
    },
    share (uis) {
      let clipboard = weex.requireModule('clipboard')
      let weixinApi = weex.requireModule('weixinApi')
      let text = this.getShareContent(uis.content)
      clipboard.setString(text)
      modal.toast({message: '文案已复制到剪贴板', duration: 0.5})
      this.loadingShow = true
      api.userItemSelection.share({id: uis.id}).done(rs => {
        let data = rs.data
        let images = uis.itemList.map(o => api.url.commissionItem.sharePic({id: o.id, userId: data.userId, t: new Date().getTime()}))
        // modal.alert({message: JSON.stringify(uis.itemList.map(o => api.url.commissionItem.sharePic({id: o.id, userId: data.userId, t: new Date().getTime()})))})
        weixinApi.sendTimeline({
          images: images,
          text: text
        }, (flag) => {
          if (!flag) {
            modal.alert({message: '您还没有安装微信，无法分享，请先安装微信！'})
          }
          this.loadingShow = false
        })
      })
    }
  }
}
</script>
